package com.ds.robot.assistant.job;

import com.google.common.cache.LoadingCache;
import com.google.common.collect.Lists;
import com.ds.robot.assistant.entity.EmpInfoEntity;
import com.ds.robot.assistant.service.EmpInfoService;
import com.ds.robot.assistant.util.JsonUtil;
import com.ds.robot.assistant.service.yunxiao.YunXiaoMemberClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 作用：
 *
 * @author WeiShaoying
 * 
 */
@Service
@Slf4j
@SuppressWarnings("SpellCheckingInspection")
public class YunXiaoEmpJob {

    @Autowired
    private YunXiaoMemberClient yunXiaoMemberClient;

    @Autowired
    private EmpInfoService empInfoService;

    @Resource
    private LoadingCache<String, String> userCache;

    @PostConstruct
    public void init() {
        updateUserCache();
    }

    @Scheduled(cron = "0 0 0/6 * * *")
    @Transactional(rollbackFor = Exception.class)
    public void updateOrgMembersJob() throws Exception {
        List<EmpInfoEntity> orgEmpList = yunXiaoMemberClient.queryOrgEmpList();
        if (CollectionUtils.isEmpty(orgEmpList)) {
            log.warn("查询组织人员为空，任务结束");
            return;
        }
        List<EmpInfoEntity> dbList = empInfoService.list();
        Map<String, EmpInfoEntity> entityMap = new HashMap<>();

        if (!CollectionUtils.isEmpty(dbList)) {
            entityMap = dbList.stream().collect(Collectors.toMap(EmpInfoEntity::getAccountId, Function.identity()));
        }

        List<EmpInfoEntity> needSaveList = Lists.newArrayList();
        List<EmpInfoEntity> needUpdateList = Lists.newArrayList();
        for (EmpInfoEntity emp : orgEmpList) {
            if (!entityMap.containsKey(emp.getAccountId())) {
                needSaveList.add(emp);
            } else {
                EmpInfoEntity empDb = entityMap.get(emp.getAccountId());
                if (!empDb.equals(emp)) {
                    emp.setId(empDb.getId());
                    needUpdateList.add(emp);
                }
            }
        }
        if (!CollectionUtils.isEmpty(needSaveList)) {
            boolean b = empInfoService.saveBatch(needSaveList);
            log.info("批量新增人员成功? {}，员工数量：{}", b, needSaveList.size());
        }
        if (!CollectionUtils.isEmpty(needUpdateList)) {
            log.info("需要更新的人员：{}", JsonUtil.toJson(needUpdateList));
            boolean b = empInfoService.saveOrUpdateBatch(needUpdateList);
            log.info("批量更新人员成功? {}，员工数量：{}", b, needUpdateList.size());
        }
    }


    @Scheduled(cron = "0 30 0/6 * * *")
    public void updateUserCache() {
        log.info("==== 开始更新UserCache");
        List<EmpInfoEntity> empList = empInfoService.list();
        if (!CollectionUtils.isEmpty(empList)) {
            for (EmpInfoEntity entity : empList) {
                userCache.put(entity.getAccountId(), entity.getName());
            }
        }
        log.info("==== 更新UserCache完成");
    }

}
